package DMSXL._2024.BinaryTrees;

import com.sun.source.tree.Tree;

import java.util.LinkedList;
import java.util.Queue;

public class isBalanced {
    public static void main(String[] args) {
        Integer[] nums = {1,null,2,null,3};
        TreeNode root = CreateTree.createBinaryTree(nums,0);
        System.out.println(new isBalanced().isBalanced(root));
    }
    public boolean isBalanced(TreeNode root) {
        return getHeight(root) != -1;
    }

    private int getHeight(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int leftHeight = getHeight(root.left);
        if (leftHeight == -1) {
            return -1;
        }
        int rightHeight = getHeight(root.right);
        if (rightHeight == -1) {
            return -1;
        }
        // 左右子树高度差大于1，return -1表示已经不是平衡树了
        if (Math.abs(leftHeight - rightHeight) > 1) {
            return -1;
        }
        return Math.max(leftHeight, rightHeight) + 1;
    }




}
